import { ref, reactive, computed, onActivated } from "vue"
import { useRouter, useRoute } from "vue-router"
// 校验函数
import { validateRequired, formatTree } from "@/utils/index"
// ant
import { message } from "ant-design-vue"
// api
import { libraryadd, libraryupdate, librarydetailed } from "@/api/index"
// dict
import { useDict } from "@/dict/index"
import { useSelectAsync } from "@/hook/index"
export function useForm(){
  const router = useRouter()
  const route = useRoute()
  const { useDictList } = useDict()
  const { useGetUserAll, useGetLiteratureAll } = useSelectAsync()
  const literatureTypeList = ref([])
  const uesSaveLoading = ref(false)
  const state = reactive({
    id: route.params?.id,
    defaultArea: [],
    controlList: [
      { 
        label: "藏馆名称", 
        field: "library_name", 
        control: "input", 
        maxlength: 20,
        rules: [validateRequired("请输入藏馆名称")]
      },
      { 
        label: "楼层", 
        field: "library_floor", 
        control: "select", 
        options: useDictList('floorModules'),
        rules: [validateRequired("请选择楼层")]
      },
      { 
        label: "文献类型", 
        field: "literature_id", 
        type: 'slot',
        slotName: "literatureType",
        rules: [validateRequired("请选择文献类型")]
      },
      { 
        label: "咨询电话", 
        field: "library_tel", 
        control: "input", 
        maxlength: 20,
        rules: [validateRequired("请输入咨询电话")]
      },
      { 
        label: "投诉电话", 
        field: "consult_tel", 
        control: "input", 
        maxlength: 20,
        rules: [validateRequired("请输入投诉电话")]
      },
      { 
        label: "藏馆状态", 
        field: "library_status", 
        control: "select", 
        options: useDictList('libraryStatusModules'),
        rules: [validateRequired("请选择藏馆状态")]
      },
      { 
        label: "建馆日期", 
        field: "library_date", 
        control: "date", 
        showTime: false,
        valueFormat: "YYYY-MM-DD",
        rules: [validateRequired("请选择建馆日期")]
      },
      { 
        label: "藏馆管理员", 
        field: "library_admin", 
        control: "select", 
        id: "member_id",
        name: "username",
        mode: "multiple",
        optionsAsync: useGetUserAll,
        rules: [validateRequired("请选择藏馆管理员")]
      },
      { 
        label: "藏馆邮箱", 
        field: "library_email", 
        control: "input", 
        maxlength: 20,
        rules: [validateRequired("请输入藏馆邮箱")]
      },
      { 
        label: "省市区", 
        field: "area", 
        control: "area", 
        name: "name",
        id: "code",
        defaultValue: [],
        rules: [validateRequired("请选择省市区")]
      },
      { 
        label: "详细地址", 
        field: "address", 
        control: "textarea", 
        maxlength: 500,
        rules: [validateRequired("请输入详细地址")]
      },
    ],
    fields: {
      library_name: "",
      library_floor: undefined,
      literature_id: [],
      library_tel: "",
      consult_tel: "",
      library_status: undefined,
      library_date: "",
      library_admin: [],
      library_email: "",
      province: 0,
      city: 0,
      area: 0,
      address: "",
    }
  })
  // 是否有id存在
  const hasId = computed(() => state.id)
  /**
   * changeSelect
   */
  const useChangeSelect = (value, option) => {
      literatureTypeList.value = option
  }
  /**
   * 删除文献类型
   */
  const useDeleteLiteratureItem = (idx) => {
      state.fields.literature.splice(idx, 1)
      literatureTypeList.value.splice(idx, 1)
  }

  const getControl = (data, key) => {
    const control = data.filter(item => item.field === key)
    if(control.length) {
      return control[0]
    }
  }

  /**
   * 获取详情
   */
  const useGetDetailed = () => {
    librarydetailed({id: state.id}).then(res => {
      state.fields = res.content
      // 文献类型列表
      literatureTypeList.value = res.content.literature_arr
      // 获取控件
      const control = getControl(state.controlList, 'area')
      control.defaultValue = formatTree(res.content.ids, 'code', 'parent_id')
     
    })
  }

  /**
   * 保存
   */
  const useSave = () => {
    hasId.value ? handleUpdate() : handleAdd()
  }

  /**
   * 新建
   */
  const handleAdd = () => {
    state.fields.province = state.fields.area[0]
    state.fields.city = state.fields.area[1]
    state.fields.area = state.fields.area[2]
    uesSaveLoading.value = true
    libraryadd(state.fields).then((res) => {
      message.success(res?.msg)
      router.go(-1)
      uesSaveLoading.value = false
    }).catch(() => {
      uesSaveLoading.value = false
    })
  }

  /**
   * 新建
   */
  const handleUpdate = () => {
    state.fields.province = state.fields.area[0]
    state.fields.city = state.fields.area[1]
    state.fields.area = state.fields.area[2]
    uesSaveLoading.value = true
    libraryupdate({
      ...state.fields,
      library_id: hasId.value
    }).then((res) => {
      message.success(res?.msg)
      router.go(-1)
      uesSaveLoading.value = false
    }).catch(() => {
      uesSaveLoading.value = false
    })
  }

  onActivated(() => {
    // 是否请求详情数据
    hasId.value && useGetDetailed()
  })
  
  return {
      state,
      useChangeSelect,
      literatureTypeList,
      useGetLiteratureAll,
      useDeleteLiteratureItem,
      useSave,
      uesSaveLoading,
      hasId
  }
}